#include "wificonfig.h"
#include <PubSubClient.h>
#include "string.h"

WiFiClient espClient;
PubSubClient client(espClient);
char topic[20];
char msg[101];

char s[10];
void(* resetFun) (void) = 0;
void reconnect() 
{
  // Loop until we're reconnected
  while (!client.connected()) {
    #if DEBUG_ON
    Serial.println("Attempting MQTT connection...");
    #endif
    topic[0]='A';
    if (client.connect(topic,username.c_str(),userpass.c_str())) {
      #if DEBUG_ON
      Serial.println("connected");
      #endif
      // Once connected, publish an announcement...
      //client.publish("outTopic", "hello world");
      // ... and resubscribe 
      topic[0]='D'; 
      client.subscribe(topic);
      #if DEBUG_ON
      Serial.println("subscribe:");
      Serial.println(topic);
      break;
      #endif
    }else {
      #if DEBUG_ON
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      #endif
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void callback(char* topic, byte* payload, unsigned int length) {
  char len = strlen(topic);
  char message[101];
  memset(message,0,101);
    for (int i = 0; i < length; i++) {
    message[i]=(char)payload[i];
  }
  Serial.println(message);
}
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  SPIFFS.begin();
  
  WiFi.macAddress(MAC_array_STA);
  sprintf(&topic[1],"%d%d%d%d%d%d",MAC_array_STA[0],MAC_array_STA[1],MAC_array_STA[2],MAC_array_STA[3],MAC_array_STA[4],MAC_array_STA[5]);
  delay(1000);
  topic[0]='A';
  Serial.print("device id : ");
  Serial.println(topic);
  #if DEBUG_ON
  Serial.println(int(MAC_array_STA[0]));
  Serial.println(int(MAC_array_STA[1]));
  Serial.println(int(MAC_array_STA[2]));
  Serial.println(int(MAC_array_STA[3]));
  Serial.println(int(MAC_array_STA[4]));
  Serial.println(int(MAC_array_STA[5]));
  #endif
  if( SPIFFS.exists(config_file_name)) setWifi();
  else WiFiInit();

  #if DEBUG_ON
  Serial.println("out of wifi function");
  Serial.println(WiFi.localIP());
  #endif
  Serial.setTimeout(1000);
  
  
  Serial.readBytesUntil('\n',s,2);
  if(s[0]=='R') {SPIFFS.remove(config_file_name);resetFun();}
  
  client.setServer(ip.c_str(),port.toInt());
  client.setCallback(callback);
  #if DEBUG_ON
  Serial.println(WiFi.localIP());
  #endif
  char i = 0;
  while(WiFi.status()!=WL_CONNECTED || i<10)
  {
    delay(1000);
    i++;
  }
  if(WiFi.status()==WL_CONNECTED) Serial.println("OK");
  else Serial.println("XX");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  uint8_t len = Serial.readBytesUntil('\n',msg,100);
  if(len>=1 && msg[len-1])
  {
    topic[0]='U';
    client.publish(topic, msg);
    memset(msg,0,30);
  }
  
}
